<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <title>OpenLayers Map</title>
  <style>
    html, body, iframe {
      height: 100%;
    }
    body {
      margin: 0;
    }
    iframe {
      width: 100%;
      border: 0;
      display: block;
    }
    .toolbar {
      position: fixed;
      top: 1cm;
      left: 1cm;
    }
    input {
      text-transform: uppercase;
    }
  </style>
</head>

<body>
  <iframe onload="lnm(this)" src="/ol/index.html" title="OpenLayers map"></iframe>
  <script>
    /**
     * Plugin embedding
     * the littlenavmap-openlayers implementation
     * 
     * See: 
     * - https://github.com/KOKAProduktion/littlenavmap-openlayers
     * - /web/ol (dist of littlenavmap-openlayers)
     */

    var littlenavmap;

    function init(message) {
      var ppi = message.pluginParent.callback(message.pluginParent.callback.TYPE_EXCLUSIVE, stop);
      
      var toolbar = ppi.toolbarAPI.createToolbar(document.body);
      var b;
      var ti = ppi.toolbarAPI.createTextInput({
        text: "ICAO",
        handlerNames: "keydown",
        "keydown": e => {
          if(e.key === "Enter") {
            b.click();
            e.stopPropagation();
            e.preventDefault();
          }
        }
      }, toolbar);
      b = ppi.toolbarAPI.createButton({
        text: "Find",
        handlerNames: "click",
        click: () => {
          var ident = ti.value;
          fetch("/api/airport/info?ident=" + ident).then((response) => {
            return response.json();
          }).then((json) => {
            // turn off aircraft follow
            if (littlenavmap.following) {
              littlenavmap.map.getControls().getArray()[0].handleFollow();
            }
            // move to airport position
            littlenavmap.moveTo([json.position.lon, json.position.lat]);
          }).catch((error) => {
            console.log(error);
          })
        }
      }, toolbar);
      
      ppi.run()
    }

    function stop() {}

    function lnm(iframe) {
      littlenavmap = iframe.contentWindow.littlenavmap;
    }
  </script>
</body>

</html>